package com.isoft.airportsystem.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.airportsystem.entity.system.Permission;
import com.isoft.airportsystem.entity.system.RolePermission;
import com.isoft.airportsystem.mapper.system.PermissionMapper;
import com.isoft.airportsystem.mapper.system.RolePermissionMapper;
import com.isoft.airportsystem.service.system.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Permission> selectPermissionList(Permission permission) {
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        if (permission != null) {
            // 根据权限名称模糊查询
            if (StringUtils.hasText(permission.getPermissionName())) {
                queryWrapper.like(Permission::getPermissionName, permission.getPermissionName());
            }
            // 根据权限标识模糊查询
            if (StringUtils.hasText(permission.getPermissionCode())) {
                queryWrapper.like(Permission::getPermissionCode, permission.getPermissionCode());
            }
            // 根据权限类型查询
            if (permission.getPermissionType() != null) {
                queryWrapper.eq(Permission::getPermissionType, permission.getPermissionType());
            }
            // 根据状态查询
            if (permission.getStatus() != null) {
                queryWrapper.eq(Permission::getStatus, permission.getStatus());
            }
            // 根据父权限ID查询
            if (permission.getParentId() != null) {
                queryWrapper.eq(Permission::getParentId, permission.getParentId());
            }
        }
        // 只查询未删除的权限
        queryWrapper.eq(Permission::getDelFlag, 0);
        // 按排序升序排序
        queryWrapper.orderByAsc(Permission::getSort);
        return list(queryWrapper);
    }

    @Override
    public List<Permission> selectPermissionsByRoleId(Long roleId) {
        return baseMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<Permission> selectPermissionsByUserId(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public List<Permission> selectMenuList() {
        return baseMapper.selectMenuList();
    }

    @Override
    public List<Permission> selectMenuListByUserId(Long userId) {
        return baseMapper.selectMenuListByUserId(userId);
    }

    @Override
    public boolean insertPermission(Permission permission) {
        // 设置默认值
        permission.setCreateTime(LocalDateTime.now());
        permission.setDelFlag(0);
        return save(permission);
    }

    @Override
    public boolean updatePermission(Permission permission) {
        // 设置更新时间
        permission.setUpdateTime(LocalDateTime.now());
        return updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePermissionById(Long permissionId) {
        // 检查是否有子权限
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getParentId, permissionId);
        queryWrapper.eq(Permission::getDelFlag, 0);
        long count = count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("存在子权限，不能删除");
        }
        // 逻辑删除权限
        Permission permission = new Permission();
        permission.setPermissionId(permissionId);
        permission.setDelFlag(1);
        permission.setUpdateTime(LocalDateTime.now());
        boolean result = updateById(permission);
        // 删除角色权限关联
        if (result) {
            LambdaQueryWrapper<RolePermission> rolePermissionQueryWrapper = new LambdaQueryWrapper<>();
            rolePermissionQueryWrapper.eq(RolePermission::getPermissionId, permissionId);
            rolePermissionMapper.delete(rolePermissionQueryWrapper);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePermissionByIds(Long[] permissionIds) {
        // 检查是否有子权限
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Permission::getParentId, Arrays.asList(permissionIds));
        queryWrapper.eq(Permission::getDelFlag, 0);
        long count = count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("存在子权限，不能删除");
        }
        // 批量逻辑删除权限
        List<Permission> permissionList = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            Permission permission = new Permission();
            permission.setPermissionId(permissionId);
            permission.setDelFlag(1);
            permission.setUpdateTime(LocalDateTime.now());
            permissionList.add(permission);
        }
        boolean result = updateBatchById(permissionList);
        // 批量删除角色权限关联
        if (result) {
            LambdaQueryWrapper<RolePermission> rolePermissionQueryWrapper = new LambdaQueryWrapper<>();
            rolePermissionQueryWrapper.in(RolePermission::getPermissionId, Arrays.asList(permissionIds));
            rolePermissionMapper.delete(rolePermissionQueryWrapper);
        }
        return result;
    }

    @Override
    public List<Permission> selectPermissionTree() {
        // 查询所有权限
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getStatus, 1);
        queryWrapper.eq(Permission::getDelFlag, 0);
        queryWrapper.orderByAsc(Permission::getSort);
        List<Permission> allPermissions = list(queryWrapper);

        // 构建树结构
        return buildPermissionTree(allPermissions);
    }

    /**
     * 构建权限树结构
     *
     * @param allPermissions 所有权限列表
     * @return 权限树
     */
    private List<Permission> buildPermissionTree(List<Permission> allPermissions) {
        // 按父ID分组
        Map<Long, List<Permission>> parentMap = allPermissions.stream()
                .collect(Collectors.groupingBy(permission ->
                        permission.getParentId() == null ? 0L : permission.getParentId()));

        // 递归构建树
        return buildTreeRecursive(parentMap, 0L);
    }

    /**
     * 递归构建树结构
     *
     * @param parentMap 父ID映射
     * @param parentId  父ID
     * @return 子权限列表
     */
    private List<Permission> buildTreeRecursive(Map<Long, List<Permission>> parentMap, Long parentId) {
        List<Permission> children = parentMap.get(parentId);
        if (children == null) {
            return new ArrayList<>();
        }

        for (Permission permission : children) {
            List<Permission> childList = buildTreeRecursive(parentMap, permission.getPermissionId());
            // 这里可以设置子权限列表，如果Permission实体有children字段的话
        }

        return children;
    }
}